package com.ruicar.afs.cloud.admin.controller;


import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.common.core.security.annotation.Inner;
import com.ruicar.afs.cloud.admin.entity.SysLog;
import com.ruicar.afs.cloud.admin.service.SysLogService;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Arrays;

/**
 * <p>
 * 日志表 前端控制器
 * </p>
 *
 * @author Fzero
 * @since 2017-11-20
 */
@RestController
@AllArgsConstructor
@RequestMapping("/log")
@Api(value = "log", description = "日志管理模块")
public class LogController {
	private final SysLogService sysLogService;


	@GetMapping(value = "/getAllByPage")
	@ApiOperation(value = "分页获取全部")
	public IResponse<Object> getAllByPage(
			@RequestParam(required = false) String type,
			@RequestParam(required = false) String startDate,
			@RequestParam(required = false) String endDate,
			@RequestParam(required = false) String title,
			@RequestParam(name = "pageNumber") int pageNumber, @RequestParam(name = "pageSize") int pageSize) {

		return new IResponse().setData(sysLogService.page(new Page(pageNumber, pageSize)
				, Wrappers.<SysLog>query().lambda()
						.eq(StringUtils.isNotEmpty(title), SysLog::getTitle, title)
						.ge(StringUtils.isNotEmpty(startDate), SysLog::getCreateTime, StringUtils.isNotEmpty(startDate)?DateUtil.parse(startDate,"yyyy-MM-dd"):null)
						.le(StringUtils.isNotEmpty(endDate), SysLog::getCreateTime, StringUtils.isNotEmpty(endDate)?DateUtil.parse(endDate,"yyyy-MM-dd"):null)
						.eq(StringUtils.isNotEmpty(type), SysLog::getType, type)));
	}

	@DeleteMapping(value = "/delByIds/{ids}")
	@ApiOperation(value = "批量删除")
	@Transactional
	public IResponse<Boolean> delByIds(@PathVariable String[] ids) {
		sysLogService.removeByIds(Arrays.asList(ids));
		return new IResponse().setMsg("删除成功");
	}

	@DeleteMapping(value = "/delAll")
	@ApiOperation(value = "全部删除")
	@Transactional
	public IResponse<Object> delAll() {
		sysLogService.remove(Wrappers.<SysLog>update().lambda().ne(SysLog::getId, ""));
		return new IResponse<Object>().setMsg("删除成功");
	}

	/**
	 * 插入日志
	 *
	 * @param sysLog 日志实体
	 * @return success/false
	 */
	@PostMapping("/save")
	public IResponse save(@Valid @RequestBody SysLog sysLog) {
		return new IResponse<>(sysLogService.save(sysLog));
	}


}
